package com.example.demo.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.springframework.scheduling.annotation.Async;

import net.sf.json.JSONObject;

public class Util {
	
	public static JSONObject interfaceUtil(String path) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //PrintWriter out = null;
            
            /**设置URLConnection的参数和普通的请求属性****start***/
           
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
            
            /**设置URLConnection的参数和普通的请求属性****end***/
            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            conn.setRequestMethod("GET");//GET和POST必须全大写
            /**GET方法请求*****start*/
            /**
             * 如果只是发送GET方式请求，使用connet方法建立和远程资源之间的实际连接即可；
             * 如果发送POST方式的请求，需要获取URLConnection实例对应的输出流来发送请求参数。
             * */
            conn.connect(); 
            
            /**GET方法请求*****end*/
            
            /***POST方法请求****start*/
            /*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流 
            
            out.print(data);//发送请求参数即数据
            
            out.flush();//缓冲数据
            */            
            /***POST方法请求****end*/
            
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while (((str = br.readLine()) != null)) {
            	str=new String(str.getBytes(),"UTF-8");//解决中文乱码问题
            	break;
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            if (str != "") {
            	 JSONObject jsonObject =JSONObject.fromObject(str);
                 return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	@Async("taskExecutor")
	public static void getArea(HttpServletRequest request) {
		JSONObject jo = interfaceUtil("http://www.weather.com.cn/data/city3jdata/china.html");
		Iterator<String> allKeys = jo.keys();
//		Map<String, String> provinceMap = new HashMap<String, String>();
//		Map<String, String> cityMap = new HashMap<String, String>();
		Map<String, String> stationMap = new HashMap<String, String>();
		while(allKeys.hasNext()){
            String key = allKeys.next();
//            String province = jo.optString(key);
//            provinceMap.put(province, key);
            String url2 = "http://www.weather.com.cn/data/city3jdata/provshi/" +  key + ".html";
            JSONObject jo2 = interfaceUtil(url2);
            Iterator<String> allKeys2 = jo2.keys();
            while (allKeys2.hasNext()) {
            	String cityKey = allKeys2.next();
            	String key2 = key + cityKey;
//            	String city = jo2.optString(cityKey);
//            	cityMap.put(city, key2);
            	String url3 = "http://www.weather.com.cn/data/city3jdata/station/" +  key2 + ".html";
            	JSONObject jo3 = interfaceUtil(url3);
            	Iterator<String> allKeys3 = jo3.keys();
            	while (allKeys3.hasNext()) {
            		String stationKey = allKeys3.next();
            		String key3 = key2 + stationKey;
            		String station = jo3.optString(stationKey);
            		stationMap.put(station, key3);
            	}
            }
        }
//		request.getSession().setAttribute("province", provinceMap);
//		request.getSession().setAttribute("city", cityMap);
		request.getSession().setAttribute("station", stationMap);
	}

//	public Optional<Integer> getTemperature(String province, String city, String county) {
//		Optional<Integer> opt = Optional.ofNullable(0);
//		return opt;
//	}
	
}
